package com.xjmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.xjmall.common.Const;
import com.xjmall.common.ResponseCode;
import com.xjmall.common.ServerResponse;
import com.xjmall.common.ServerResult;
import com.xjmall.dao.*;
import com.xjmall.exception.DataNotFoundException;
import com.xjmall.exception.ParameterCheckException;
import com.xjmall.pojo.*;
import com.xjmall.service.ICategoryService;
import com.xjmall.service.IProductService;
import com.xjmall.util.DateTimeUtil;
import com.xjmall.util.PropertiesUtil;
import com.xjmall.vo.ProductDetailVo;
import com.xjmall.vo.ProductListVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by An on 2017/5/17.
 */
@Service("iProductService")
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ICategoryService iCategoryService;
    @Autowired
    private SpecificationsMapper specificationsMapper;
    @Autowired
    private AccessoryGroupMapper accessoryGroupMapper;
    @Autowired
    private CommentMapper commentMapper;

    /**
     * 保存商品信息
     * @param product 待保存的商品信息
     * @return ServerResult
     */
    @Override
    public ServerResult saveOrUpdateProduct(Product product) {
        // 校验商品信息
        if (product == null) {
            throw new ParameterCheckException("添加或更新产品的参数不正确");
        }
        if (StringUtils.isNotBlank(product.getSubImages())) {
            String[] subImageArray = product.getSubImages().split(",");
            if (subImageArray.length > 0) {
                product.setMainImage(subImageArray[0]);
            }
        }
        if (product.getId() != null) {
            int count = productMapper.updateByPrimaryKeySelective(product);
            if (count < 1) {
                throw new DataNotFoundException("更新产品失败");
            }
            return ServerResult.successMsg("更新产品成功");
        } else {
            int count = productMapper.insertSelective(product);
            if (count < 1) {
                throw new DataNotFoundException("添加产品失败");
            }
            return ServerResult.successMsg("添加产品成功");
        }
    }

    /**
     * 修改产品销售状态（上下架）
     * @param productId 商品id
     * @param status 商品销售状态
     * @return ServerResult
     */
    @Override
    public ServerResult setSaleStatus(Integer productId, Integer status) {
        // 参数校验
        if (productId == null || status == null) {
            throw new ParameterCheckException("空参数");
        }
        if (status != Const.ProductStatusEnum.ON_SALE.getCode() || status != Const.ProductStatusEnum.OFF_SALE.getCode()) {
            throw new ParameterCheckException("非法参数");
        }
        Product product = new Product();
        product.setId(productId);
        product.setStatus(status);
        int updateCount = productMapper.updateByPrimaryKeySelective(product);
        if (updateCount < 1) {
            throw new DataNotFoundException("修改产品销售状态失败");
        }
        return ServerResult.successMsg("修改产品销售状态成功");
    }

    /**
     * 根据商品id获取商品详情
     * @param productId 商品id
     * @return ServerResult
     */
    @Override
    public ServerResult getManageProductDetail(Integer productId) {
        // 参数校验
        if (productId == null) {
            throw new ParameterCheckException("空参数");
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null) {
            throw new DataNotFoundException("产品已经删除");
        }
        // 查询该商品的颜色分类信息
        List<Specifications> specList = specificationsMapper.selectByProductId(productId);
        // 查询该商品的套餐信息
        List<AccessoryGroup> accessList = accessoryGroupMapper.selectByProductId(productId);
        ProductDetailVo vo = assembleProductDetailVo(product, specList, accessList);
        return ServerResult.successData(vo);
    }

    /**
     * 商品列表
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return ServerResult
     */
    @Override
    public ServerResult getProductList(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productMapper.selectList();
        List<ProductListVo> productListVoList = Lists.newArrayList();
        for (Product item : productList) {
            ProductListVo vo = assembleProductListVo(item);
            productListVoList.add(vo);
        }
        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(productListVoList);
        return ServerResult.successData(pageInfo);
    }

    /**
     * 根据搜索条件查询商品列表
     * @param productName 商品名称
     * @param productId 商品id
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return ServerResult
     */
    @Override
    public ServerResult searchProduct(String productName, Integer productId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotBlank(productName)) {
            productName = new StringBuilder().append("%").append(productName).append("%").toString();
        }
        List<Product> productList = productMapper.selectByNameAndProductId(productName, productId);
        List<ProductListVo> productListVoList = Lists.newArrayList();
        for (Product item : productList) {
            ProductListVo vo = assembleProductListVo(item);
            productListVoList.add(vo);
        }
        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(productListVoList);
        return ServerResult.successData(pageInfo);
    }

    /**
     * 根据分类id查询商品列表
     * @param categoryId 分类id
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return ServerResult
     */
    @Override
    public ServerResult getProductByCategoryId(Integer categoryId, int pageNum, int pageSize) {
        // 参数校验
        if (categoryId == null) {
            throw new ParameterCheckException("空参数");
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productMapper.selectByCategoryId(categoryId);
        List<ProductListVo> voList = Lists.newArrayList();
        for (Product product : productList) {
            ProductListVo vo = assembleProductListVo(product);
            voList.add(vo);
        }
        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(voList);
        return ServerResult.successData(pageInfo);
    }

    @Override
    public ServerResponse<PageInfo> getProductByKeywordCategory(String keyword, Integer categoryId, int pageNum, int pageSize, String orderBy) {
        if (StringUtils.isBlank(keyword) && categoryId == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        List<Integer> categoryIdList = new ArrayList<Integer>();
        if (categoryId != null) {
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            if (category == null && StringUtils.isBlank(keyword)) {
                PageHelper.startPage(pageNum, pageSize);
                List<ProductListVo> voList = Lists.newArrayList();
                PageInfo pageInfo = new PageInfo(voList);
                return ServerResponse.createBySuccess(pageInfo);
            }
            categoryIdList = iCategoryService.selectCategoryAndChildrenById(category.getId()).getData();
        }
        if (StringUtils.isNotBlank(keyword)) {
            keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
        }
        PageHelper.startPage(pageNum, pageSize);
        // 排序
        if (StringUtils.isNotBlank(orderBy)) {
            if (Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)) {
                String[] orderByArray = orderBy.split("_");
                PageHelper.orderBy(orderByArray[0] + " " + orderByArray[1]);
            }
        }
        List<Product> productList = productMapper.selectByNameAndCategoryIds(StringUtils.isBlank(keyword) ? null : keyword, categoryIdList.size() == 0 ? null : categoryIdList);
        List<ProductListVo> voList = Lists.newArrayList();
        for (Product product : productList) {
            ProductListVo vo = assembleProductListVo(product);
            voList.add(vo);
        }
        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(voList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse<ProductDetailVo> getProductDetail(Integer productId) {
        if (productId == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null) {
            return ServerResponse.createByErrorMessage("产品已删除");
        }
        if (product.getStatus() != Const.ProductStatusEnum.ON_SALE.getCode()) {
            return ServerResponse.createByErrorMessage("产品已下架");
        }
        // 查询该商品的颜色分类信息
        List<Specifications> specList = specificationsMapper.selectByProductId(productId);
        // 查询该商品的套餐信息
        List<AccessoryGroup> accessList = accessoryGroupMapper.selectByProductId(productId);
        ProductDetailVo vo = assembleProductDetailVo(product, specList, accessList);
        int commentCount = commentMapper.selectCountByProductId(productId);
        vo.setCommentCount(commentCount);
        return ServerResponse.createBySuccess(vo);
    }



    /**
     * 查询新品上架的商品列表
     * @return
     */
    public ServerResponse<List<ProductListVo>> selectNewProductList() {
        List<Product> newProductList = productMapper.selectNewProductList();
        List<ProductListVo> voList = Lists.newArrayList();
        for (Product product : newProductList) {
            ProductListVo vo = assembleProductListVo(product);
            voList.add(vo);
        }
        return ServerResponse.createBySuccess(voList);
    }

    /**
     * 查询疯狂热卖的商品列表
     * @return
     */
    @Override
    public ServerResponse<List<ProductListVo>> selectHotProductList() {
        List<Product> hotProductList = productMapper.selectHotProductList();
        List<ProductListVo> voList = Lists.newArrayList();
        for (Product product : hotProductList) {
            ProductListVo vo = assembleProductListVo(product);
            voList.add(vo);
        }
        return ServerResponse.createBySuccess(voList);
    }

    private ProductDetailVo assembleProductDetailVo(Product product, List<Specifications> specList, List<AccessoryGroup> accessList) {
        ProductDetailVo vo = new ProductDetailVo();
        vo.setId(product.getId());
        vo.setSubtitle(product.getSubtitle());
        vo.setPrice(new DecimalFormat("0.00").format(Double.valueOf(product.getPrice()) / 100));
        vo.setSellPrice(new DecimalFormat("0.00").format(Double.valueOf(product.getSellPrice()) / 100));
        vo.setMainImage(product.getMainImage());
        vo.setSubImages(product.getSubImages());
        vo.setCategoryId(product.getCategoryId());
        vo.setDetail(product.getDetail());
        vo.setName(product.getName());
        vo.setStatus(product.getStatus());
        vo.setStock(product.getStock());
        vo.setSellCount(product.getSellCount());
        // 这里需要指定对应的图片服务器地址前缀
        vo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://127.0.0.1/"));
        // 添加该商品的颜色分类信息
        vo.setSpecList(specList);
        // 添加该商品的套餐信息
        vo.setAccessList(accessList);

        Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
        if (category == null) {
            vo.setParentCategoryId(0);// 默认为根节点
        } else {
            vo.setParentCategoryId(category.getParentId());
        }
        vo.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));
        vo.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime()));
        return vo;
    }

    private ProductListVo assembleProductListVo(Product product){
        ProductListVo productListVo = new ProductListVo();
        productListVo.setId(product.getId());
        productListVo.setName(product.getName());
        productListVo.setCategoryId(product.getCategoryId());
        // todo 这里需要指定对应的图片服务器地址前缀
        productListVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix","http://127.0.0.1/"));
        productListVo.setMainImage(product.getMainImage());
        productListVo.setPrice(new DecimalFormat("0.00").format(Double.valueOf(product.getPrice()) / 100));
        productListVo.setSellPrice(new DecimalFormat("0.00").format(Double.valueOf(product.getSellPrice()) / 100));
        productListVo.setSubtitle(product.getSubtitle());
        productListVo.setStatus(product.getStatus());
        return productListVo;
    }
}
